package com.hontech.bread.utils

import com.hontech.bread.R
import com.hontech.bread.api.advCfgQuery
import com.hontech.bread.api.downloadAdv
import com.hontech.bread.store.StoreAdvCfg
import com.hontech.bread.store.advDir
import java.io.File

class AdvPauseEvent
class AdvReadyEvent
class AdvNotFoundException(id: Long) : Exception("adv not found $id")
class AdvNotSetException : Exception("${stringById(R.string.t1733460848_456)}")

object AdvManager {

    private var advList = emptyList<StoreAdvCfg>()
    private val currents = intArrayOf(0, 0)

    fun advPath(id: Long): String {
        if (!isExists(id)) {
            throw AdvNotFoundException(id)
        }
        return File(advDir, "$id").path
    }

    private suspend fun removeFile(id: Long) = runIO {
        val file = File(advDir, "$id")
        file.delete()
    }

    private fun isExists(id: Long): Boolean {
        val file = File(advDir, "$id")
        return file.exists()
    }

    suspend fun init2() {
        postEvent(AdvPauseEvent())

        for (i in currents.indices) {
            currents[i] = 0
        }

        try {
            initWithNet()
        } catch (e: Exception) {
            e.printStackTrace()
            initWithLocal()
        }

        postEvent(AdvReadyEvent())
    }

    private suspend fun initWithNet() {
        val list = advCfgQuery()
        val localList = StoreAdvCfg.query()

        for (adv in localList) {
            if (!list.contains(adv)) {
                adv.delete()
                removeFile(adv.advId)
            }
        }

        for (adv in list) {
            if (localList.contains(adv)) {
                if (isExists(adv.advId)) {
                    continue
                }
                runNewThread { downloadAdv(adv.advId) }
                continue
            }
            runNewThread { downloadAdv(adv.advId) }
            adv.create()
        }

        advList = list
    }

    private suspend fun initWithLocal() {
        val list = StoreAdvCfg.query()
        for (adv in list) {
            if (!isExists(adv.advId)) {
                adv.delete()
            }
        }
        advList = StoreAdvCfg.query()
    }

    fun isReady() = advList.isNotEmpty()

    fun playNext(position: Int): StoreAdvCfg {
        if (position > 1) {
            throw IllegalStateException(stringById(R.string.t1733460848_457))
        }

        if (advList.isEmpty()) {
            throw IllegalStateException(stringById(R.string.t1733460848_458))
        }

        val count = advList.size

        var index = currents[position]
        for (i in 0 until count) {
            val k = index.mod(count)
            val adv = advList[k]
            if ((adv.position == position) && adv.isAllowTime() && isExists(adv.advId)) {
                currents[position] = (index + 1).mod(count)
                return adv
            }
            index += 1
        }
        throw AdvNotSetException()
    }

}
















